/**
 * Live GPS Tracking Application
 * Loads a set of tracks from the network
 *
 * Copyright 2009, Ivar Clemens
 */

package nl.ivarclemens.gpstrack.track;

import java.io.*;
import javax.microedition.io.*;
import nl.ivarclemens.StringReader;

public class NetworkSource {
    
    public static TrackList loadTracks(String url)
    {
        TrackList trackList = new TrackList();
        MemTrack track = null;

        StringReader sr = null;

        try {
            InputStream is = (InputStream) Connector.openInputStream(url);
            sr = new StringReader(is);
        } catch(Exception e) {
            return trackList;
        }

        long count = 0;

        while(!sr.finished()) {
            String line = sr.readString();

            if(line.length() < 4)
                continue;

            if(line.substring(0, 3).compareTo("TRK") == 0) {
                if(track != null)
                    trackList.addTrack(track);

                count = 0;
                track = new MemTrack(line.substring(3));
            } else if(line.substring(0, 3).compareTo("PNT") == 0) {
                String latlon = line.substring(4);
                int space = latlon.indexOf(",");

                if(space == -1)
                    continue;

                double lat = Double.parseDouble(latlon.substring(0, space));
                double lon = Double.parseDouble(latlon.substring(space + 1));

                track.appendPosition(count++, lat, lon);
            }
        }

        if(track != null)
            trackList.addTrack(track);

        return trackList;
    }

}
